package com.javafm.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JdkHttpUtil {
    private JdkHttpUtil() {}

    public static String get(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        InputStream is = urlConnection.getInputStream();
        BufferedReader reader =new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        reader.close();
        is.close();
        return content.toString();
    }

    public static String post(String urlStr, byte[] payload) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");

        urlConnection.setDoOutput(true); // 设置参数输入，在POST请求这个必须设置为true
        OutputStream os = urlConnection.getOutputStream();
        os.write(payload); // 写入数据
        os.flush(); // 刷新，这一步一定不要忘记了
        os.close();

        InputStream is = urlConnection.getInputStream();
        BufferedReader reader =new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        reader.close();
        is.close();
        return content.toString();
    }
}
